package com.axcessfinancial.quartz;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.axcessfinancial.common.ConnectionStatus;
import com.axcessfinancial.common.MailUtil;
import com.axcessfinancial.common.ServerMap;

public class JobMonitor extends QuartzJobBean {	

	private static Logger logger = Logger.getLogger(JobMonitor.class);

	private ServerMap servers;
	private MailUtil mail;
		
	public void setServers(ServerMap servers) {
		this.servers = servers;
	}
	
	public void setMail(MailUtil mail) {
		this.mail = mail;
	}
	
	protected void executeInternal(JobExecutionContext context)
			throws JobExecutionException {
		Map<String, String> webAppMap = servers.getWebApp();
		Map<String, String> customerRegistrationWsAppMap = servers
				.getCustomerRegistrationWsApp();

		pingServer(webAppMap);
		pingServer(customerRegistrationWsAppMap);
	}

	private void pingServer(Map<String, String> urls) {
		Iterator iterator = urls.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry<String, String> entry = (Entry<String, String>) iterator
					.next();
			String url = entry.getValue();

			String statusReason = "";
			
			HttpClient client = new HttpClient();
			GetMethod method = new GetMethod(url);
			try {
				int status = client.executeMethod(method);
				
				statusReason = HttpStatus.getStatusText(status);
				
				logger.info(url + " " + status + " " + statusReason);

				if (status != HttpStatus.SC_OK) {
					
					mail.sendMail(entry, status, statusReason);
				}
				
			} catch (HttpException e) {
				mail.sendMail(entry, ConnectionStatus.CONNECTION_REFUSED);
			} catch (IOException e) {
				mail.sendMail(entry, ConnectionStatus.CONNECTION_REFUSED);
			}
		}
	}
	
}